package com.code.train.service.impl;

import com.code.train.context.LoginMemberContext;
import com.code.train.domain.ConfirmOrder;
import com.code.train.domain.DailyTrainSeat;
import com.code.train.domain.DailyTrainTicket;
import com.code.train.enums.ConfirmOrderStatusEnum;
import com.code.train.feign.MemberFeign;
import com.code.train.mapper.ConfirmOrderMapper;
import com.code.train.mapper.DailyTrainSeatMapper;
import com.code.train.mapper.cust.DailyTrainTicketMapperCust;
import com.code.train.req.ConfirmOrderTicketReq;
import com.code.train.req.MemberTicketReq;
import com.code.train.resp.CommonResp;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class AfterConfirmOrderService {

    @Resource
    private DailyTrainSeatMapper dailyTrainSeatMapper;

    @Resource
    private DailyTrainTicketMapperCust dailyTrainTicketMapperCust;

    @Resource
    private MemberFeign memberFeign;

    @Resource
    ConfirmOrderMapper confirmOrderMapper;

    /**
     * 选中座位后事务处理：
     *  座位表修改售卖情况sell；
     *  余票详情表修改余票；
     *  为会员增加购票记录
     *  更新确认订单为成功
     */
//     @Transactional
     @GlobalTransactional
     public void afterDoConfirm(DailyTrainTicket dailyTrainTicket , List<DailyTrainSeat> finalSeatList, List<ConfirmOrderTicketReq> tickets, ConfirmOrder confirmOrder) {
         log.info("seata全局事务ID: {}", RootContext.getXID());
         for (int j = 0; j < finalSeatList.size(); j++) {
             DailyTrainSeat dailyTrainSeat = finalSeatList.get(j);
             DailyTrainSeat seatForUpdate = new DailyTrainSeat();
             seatForUpdate.setId(dailyTrainSeat.getId());
             seatForUpdate.setSell(dailyTrainSeat.getSell());
             seatForUpdate.setUpdateTime(new Date());
             dailyTrainSeatMapper.updateByPrimaryKeySelective(seatForUpdate);


             //计算这个站卖出去后,影响了哪些站的余票库存
             Integer startIndex = dailyTrainTicket.getStartIndex();
             Integer endIndex = dailyTrainTicket.getEndIndex();
             char[] chars = seatForUpdate.getSell().toCharArray();
             Integer maxStartIndex = startIndex - 1;
             Integer minEndIndex = endIndex + 1;
             Integer minStartIndex = 0;
             for (int i = startIndex - 1; i >= 0; i--) {
                 char aChar = chars[i];
                 if (aChar == '1') {
                     minStartIndex = i + 1;
                     break;
                 }
             }
             log.info("影响出发站区间：" + minStartIndex + "-" + maxStartIndex);

             Integer maxEndIndex = seatForUpdate.getSell().length();
             for (int i = endIndex; i < seatForUpdate.getSell().length(); i++) {
                 char aChar = chars[i];
                 if (aChar == '1') {
                     maxEndIndex = i;
                     break;
                 }
             }
             log.info("影响到达站区间：" + minEndIndex + "-" + maxEndIndex);

             dailyTrainTicketMapperCust.updateCountBySell(
                     dailyTrainSeat.getDate(),
                     dailyTrainSeat.getTrainCode(),
                     dailyTrainSeat.getSeatType(),
                     minStartIndex,
                     maxStartIndex,
                     minEndIndex,
                     maxEndIndex);

             // 调用会员服务接口，为会员增加一张车票
             MemberTicketReq memberTicketReq = new MemberTicketReq();
             memberTicketReq.setMemberId(LoginMemberContext.getId());
             memberTicketReq.setPassengerId(tickets.get(j).getPassengerId());
             memberTicketReq.setPassengerName(tickets.get(j).getPassengerName());
             memberTicketReq.setTrainDate(dailyTrainTicket.getDate());
             memberTicketReq.setTrainCode(dailyTrainTicket.getTrainCode());
             memberTicketReq.setCarriageIndex(dailyTrainSeat.getCarriageIndex());
             memberTicketReq.setSeatRow(dailyTrainSeat.getRow());
             memberTicketReq.setSeatCol(dailyTrainSeat.getCol());
             memberTicketReq.setStartStation(dailyTrainTicket.getStart());
             memberTicketReq.setStartTime(dailyTrainTicket.getStartTime());
             memberTicketReq.setEndStation(dailyTrainTicket.getEnd());
             memberTicketReq.setEndTime(dailyTrainTicket.getEndTime());
             memberTicketReq.setSeatType(dailyTrainSeat.getSeatType());
             CommonResp<Object> commonResp = memberFeign.save(memberTicketReq);
             log.info("调用member接口，返回：{}", commonResp);

             // 更新订单状态为成功
             ConfirmOrder confirmOrderForUpdate = new ConfirmOrder();
             confirmOrderForUpdate.setId(confirmOrder.getId());
             confirmOrderForUpdate.setUpdateTime(new Date());
             confirmOrderForUpdate.setStatus(ConfirmOrderStatusEnum.SUCCESS.getCode());
             confirmOrderMapper.updateByPrimaryKeySelective(confirmOrderForUpdate);
         }
     }
}
